package com.budwk.app.sqfw.services.impl;

import com.alibaba.fastjson.JSONObject;
import com.budwk.app.common.config.AppException;
import com.budwk.app.sqfw.services.XiaomiInterfaceService;
import com.xiaomi.push.sdk.ErrorCode;
import com.xiaomi.xmpush.server.Constants;
import com.xiaomi.xmpush.server.Message;
import com.xiaomi.xmpush.server.Result;
import com.xiaomi.xmpush.server.Sender;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * @title: HuaweiPushServiceImpl
 * @Author Tan
 * @Date: 2023/7/25 17:10
 * @Version 1.0
 */
@IocBean
@Slf4j
public class XiaomiInterfaceServiceImpl implements XiaomiInterfaceService {

    @Inject
    private PropertiesProxy propertiesProxy;

    private static final String OPPO_PUSH_APP_SECRET_KEY = "push.msg.xiaomi.appSecretKey";


    @Override
    public void sendXiaomiMessage(String token, String msgContent, String action, String sqfwId) {
        Constants.useOfficial();
        // 读取配置
        String appSecretKey = propertiesProxy.get(OPPO_PUSH_APP_SECRET_KEY, StringUtils.EMPTY);
        Sender sender = new Sender(appSecretKey);
        String messagePayload = "祥云小助消息提示";

        Map<String, String> clientCustomMap = new HashMap<>(2);
        clientCustomMap.put("action", action);
        clientCustomMap.put(action, sqfwId);
        clientCustomMap.put(Constants.EXTRA_PARAM_NOTIFY_EFFECT, Constants.NOTIFY_LAUNCHER_ACTIVITY);
        clientCustomMap.put("channel_id", "112181");
        Message message = new Message.Builder()
                .title("祥云小助")
                .description(msgContent)
                .payload(messagePayload)
                .extra(clientCustomMap)
                .restrictedPackageName("com.dfsjsoft.communityassistant")
                .notifyType(-1)     // 使用默认提示音提示
                .build();
        //根据regID，发送消息到指定设备上
        try {
            Result result = sender.send(message, token, 3);
            log.info("push msg to xiaomi result: {}", JSONObject.toJSONString(result));
            if (result == null) {
                throw new AppException();
            }
            if (result.getErrorCode() != ErrorCode.Success) {
                throw new AppException(result.getReason());
            }
        } catch (IOException e) {
            log.error("push msg to xiaomi error: ", e);
            throw new AppException();
        }
    }
}
